package com.jinzhi.jzapi.examination.controller;

import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.domain.LogDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.service.LogService;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.examination.pojo.ExaminationsVo;
import com.jinzhi.jzapi.examination.pojo.TestPaperVo;
import com.jinzhi.jzapi.utils.DateTimeUtil;
import com.jinzhi.jzapi.utils.MD5Util;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.MenuService;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/examinations")
public class ApiExaminationsController extends BaseController {
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private DictService dictService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ExaminationAnswerSheetService examinationAnswerSheetService;
    @Autowired
    private LogService logService;
    @Autowired
    private ExceptionAddtimeService exceptionAddtimeService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private TemplateDetailsService templateDetailsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private TrainingCertificatesService trainingCertificatesService;


    /**
     * 小程序考试批次接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/appletsSelExamination")
    @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> appletsSelExamination() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsTeachers();

        if (examinationsVos != null && examinationsVos.size() > 0) {
            for (int i = 0; i < examinationsVos.size(); i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                examinationsVos.get(i).setExamNotes(examNotes);

                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);

                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        } else {
            return ApiResult.fail("暂无考试信息！");
        }
    }

    /**
     * 考试程序端-考试信息接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/selExamination")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExamination() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsNow();
        // List<ExaminationsVo> examinationsVosceshi = examinationBatchService.selListExaminationsNowCeshi();
        //正式考试加上测试考试
        // examinationsVos.addAll(examinationsVosceshi);

        if (examinationsVos != null && examinationsVos.size() > 0) {
            for (int i = 0; i < examinationsVos.size(); i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                examinationsVos.get(i).setExamNotes(examNotes);

                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);

                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        } else {
            return ApiResult.fail("暂无考试信息！");
        }
//        if (examinationsVo != null) {
//            Map<String, String> map = new HashMap<>();
//            map.put("name", "考试须知");
//            map.put("type", "exa_exam_notes");
//            String examNotes = dictService.selDicBy(map);
//            examinationsVo.setExamNotes(examNotes);
//
//            map.clear();
//            map.put("name", "考试提交成功页广告语");
//            map.put("type", "exam_bg");
//            String backGroundImage = dictService.selDicBy(map);
//            examinationsVo.setBackGroundImage(backGroundImage);
//
//            EhCacheUtil.put("selExamination", examinationsVo);
//            return ApiResult.success(examinationsVo);
//        } else {
//            return ApiResult.fail("暂无考试信息！");
//        }
    }

    //将考生状态改为考试中
    @PostMapping("/changeState")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public boolean changeState(String id) {
        StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("id", id);
        stuSignUpDO.setState(8);
        return stuSignUpService.updateById(stuSignUpDO);
    }

    //获取服务器系统时间
    @PostMapping("/getNowDateTime")
    @Log("考试程序端-获取服务器时间")
    @ApiOperation(value = "考试程序端-获取服务器时间", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Date getNowDateTime() {
        return new Date();
    }

    /**
     * 考试程序端-考试登录接口
     *
     * @Description: 考试程序端考生登录获取考生信息，参数：考生姓名、身份证号、考号、考试批次id
     * @Param: [name, idCard, ticketNumber, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/loginExamination")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> loginExamination(String name, String idNumber, String ticketNumber, String id) {
        if (StringUtils.isBlank(name)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(idNumber)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(ticketNumber)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无考试1！");
        }

        StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("name", name, "ticket_number", ticketNumber, "id_number", idNumber, "cbatch_id", id);
        if (stuSignUpDO == null) {
            return ApiResult.fail("信息错误！");
        } else {
            //String idNumber=stuSignUpDO.getIdNumber();
            //String pw = ticketNumber.substring(ticketNumber.length()-4)+idNumber.substring(idNumber.length()-4);
            //if(!pw.equals(password)) {
            //	return ApiResult.fail("密码错误！");
            //}
            ExaminationBatchDO examinationBatchDO = examinationBatchService.selectById(Long.parseLong(id));
            if (examinationBatchDO == null) {
                return ApiResult.fail("暂无考试2！");
            } else {
                if (examinationBatchDO.getId().equals(stuSignUpDO.getCbatchId())) {
                    if (stuSignUpDO.getState().equals(3) || stuSignUpDO.getState().equals(8)) {
                        //stuSignUpDO.setState(8);
                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
                        if (bbc) {
                            Map map = new HashMap();
                            map.put("stuSignId", stuSignUpDO.getId());//考生id
                            map.put("roomNumber", stuSignUpDO.getEallocationNum());//考场号
                            map.put("name", stuSignUpDO.getName());//考生姓名
                            map.put("ticketNumber", stuSignUpDO.getTicketNumber());//考号
                            map.put("idCard", stuSignUpDO.getIdNumber());//身份证号码
                            map.put("photo", stuSignUpDO.getPhoto());//考生照片
                            map.put("seatNumber", stuSignUpDO.getTicketNumber().substring(stuSignUpDO.getTicketNumber().length() - 2));//座位号
                            map.put("state", stuSignUpDO.getState());//考生状态
                            map.put("nowDate", new Date());
                            Map<String, String> map1 = new HashMap<>();
                            map1.put("name", "允许考试切屏次数");
                            map1.put("type", "exam_allow_num");
                            map.put("allowNum", dictService.selDicBy(map1));
                            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
                            Date currentTime = new Date();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                            String dateString = formatter.format(currentTime);
                            String cookieCode = MD5Util.md5(stuSignUpDO.getTicketNumber(), dateString);
                            map.put("cookieCode", cookieCode);
                            DictDO dic = dictService.findOneByKv("type", "exam_num");
                            DictDO dic1 = dictService.findOneByKv("type", "send_num");

                            map.put("time", dic.getValue());
                            map.put("dates", dic1.getValue());
                            return ApiResult.success(map);
                        } else {
                            return ApiResult.fail("系统错误，请重试！");
                        }
                    } else {
                        return ApiResult.fail("您已进入考试或状态异常，请与监考员联系！");
                    }
                } else {
                    return ApiResult.fail("暂无考试3！");
                }
            }
        }
    }

    /**
     * 考试程序端-考试试卷接口
     *
     * @Description: 查询试卷数据，包括试卷id、试卷编号、试卷名称、题目、选项、题号;
     * 参数：考试批次id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selTeacherExaminationPaper")
    @Log("考试程序端-考试试卷接口")
    @ApiOperation(value = "考试程序端-考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selTeacherExaminationPaper(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无试卷！");
        }
        Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
        if (map == null) {
            Map mapre = new HashMap();
            ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 1);
            if (examinationPaperDO != null) {
                mapre.put("id", examinationPaperDO.getId());//试卷id
                mapre.put("name", examinationPaperDO.getName());//试卷名称
                mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号

                Map map1 = new HashMap();
                map1.put("epaperId", examinationPaperDO.getId());
                List<ExaminationQuestionsDO> ExaminationQuestionsDOs = examinationQuestionsService.findByKv("epaper_id", examinationPaperDO.getId());
                mapre.put("questions", ExaminationQuestionsDOs);//试卷试题

                EhCacheUtil.put("examinationPaperDO" + id, mapre);
                return ApiResult.success(mapre);
            } else {
                return ApiResult.fail("暂无试卷！");
            }
        } else {
            return ApiResult.success(map);
        }
    }

    /**
     * 考试程序端-考试试卷接口
     *
     * @Description: 查询试卷数据，包括试卷id、试卷编号、试卷名称、题目、选项、题号;
     * 参数：考试批次id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selExaminationPaper")
    @Log("考试程序端-考试试卷接口")
    @ApiOperation(value = "考试程序端-考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationPaper(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无试卷！");
        }
        Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
        if (map == null) {
            Map mapre = new HashMap();
            ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 1);
            if (examinationPaperDO != null) {
                mapre.put("id", examinationPaperDO.getId());//试卷id
                mapre.put("name", examinationPaperDO.getName());//试卷名称
                mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号


                Map map1 = new HashMap();
                map1.put("epaperId", examinationPaperDO.getId());
                List<TestPaperVo> testPaperVos = examinationQuestionsService.selTestPaper(map1);
                mapre.put("questions", testPaperVos);//试卷试题
                EhCacheUtil.put("examinationPaperDO" + id, mapre);


                return ApiResult.success(mapre);
            } else {
                return ApiResult.fail("暂无试卷！");
            }
        } else {
            return ApiResult.success(map);
        }
    }


    /**
     * 考试程序端-考模拟考试试卷接口
     *
     * @Description: 获得模拟考试试卷数据，包括试卷id、试卷编号、试卷名称、限时、题目、选项、题号
     * 参数：考试批次id
     * @Param: [profile_id]  证书概况id
     * @Param: [grade]  证书等级 （0高级，1中级，2初级）
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selTrainExaminationPaper")
    @Log("考试程序端-考模拟考试试卷接口")
    @ApiOperation(value = "考试程序端-考模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selTrainExaminationPaper(String profile_id, String grade) {
        if (StringUtils.isBlank(profile_id)) {
            profile_id = "1241245212023312386L"; //当前默认为  幼儿照护职业技能等级证书
        }
        if (StringUtils.isBlank(grade)) {
            return ApiResult.fail("等级错误！");
        } else {
            if (!(grade.equals("0") || grade.equals("1") || grade.equals("2")))
                return ApiResult.fail("等级错误！");
        }

        Map mapre = new HashMap(); //返回值
        mapre.put("id", "000000");//试卷id
        mapre.put("name", "");//试卷名称
        mapre.put("numbers", "");//试卷编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Date endTime = new Date(now.getTime() + 90 * 60 * 1000);//毫秒，共90分钟
        mapre.put("endTime", sdf.format(endTime));//结束时间
        ArrayList<Map> retQuestions = new ArrayList<>();

        //获得最新的理论考试批次.

//        Map<String,Object> tmap = Maps.newHashMap();
//        tmap.put("type","0");
//        tmap.put("days","180");//半年内新建的批次，超过半年的不考虑
//        tmap.put("profile_id",profile_id);
//        List<ExaminationBatchDO> examinationBatchDOs=  examinationBatchService.selListExamBatch(tmap);
//        ExaminationBatchDO examinationBatchDO = null ;
//
//        if(examinationBatchDOs!=null){
//            examinationBatchDO=examinationBatchDOs.get(0);
//        }

        //第二步，
//        if (examinationBatchDO == null) {
//            return  ApiResult.fail("对应的考试批次还没有审核，请等待！");
//        } else {
//            if (examinationBatchDO.getState().equals(0) || examinationBatchDO.getState().equals(2)) {
//                return  ApiResult.fail("该考试批次审核还未通过，请先审核！");
//            } else {

        // Long id = examinationBatchDO.getId();

        //查询认证批次信息
//                CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(examinationBatchDO.getCbatchId());
//                if (certificationBatchDO == null) {
//                    return  ApiResult.fail("对应的认证批次信息有误，请检查或重试！");
//                }

//                if (examinationBatchDO.getType().equals(0)) {//理论考试
        //查询试卷模板信息
        String newId = "";
        CertificateNewsDO cn = new CertificateNewsDO();
        Map mapdic = new HashMap();
        mapdic.put("type", "yys1");
        mapdic.put("name", "产康催乳ID设置");
        String profiled = dictService.selDicBy(mapdic);
        profile_id = profiled;
        Map mapdicgrade = new HashMap();
        mapdicgrade.put("type", "yys2");
        mapdicgrade.put("name", "产康催乳等级设置");
        String mapdicgradev = dictService.selDicBy(mapdicgrade);

        grade = mapdicgradev;
        cn = certificateNewsService.findOneByKv("profile_id", profiled, "grade", mapdicgradev);
        TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.findOneByKv("type", 0, "news_id", cn.getId());
        if (testPaperTemplateDO == null) {
            return ApiResult.fail("未找到对应的试卷模板，请检查或重试！");
        } else {
            ExaminationPaperDO examinationPaperDO1 = new ExaminationPaperDO();
            //添加考试试卷信息
            //examinationPaperDO1.setEbatchId(id);//考试批次id
            //examinationPaperDO1.setTptemplateId(testPaperTemplateDO.getId());//试卷模板id
            //examinationPaperDO1.setName(testPaperTemplateDO.getName());//试卷名称
            //examinationPaperDO1.setState(0);//状态
            //examinationPaperDO1.setDuration(testPaperTemplateDO.getDuration());//时长
            //examinationPaperDO1.setCreaterId(this.getUserId());//创建人id
            //examinationPaperDO1.setCreaterDate(new Date());//创建时间

            List<ExaminationQuestionsDO> examinationQuestionsDOS = new ArrayList<>();
            //查询试卷模板详情
            List<TemplateDetailsDO> templateDetailsDOs = templateDetailsService.findByKv("tptemplate_id", testPaperTemplateDO.getId());
            if (templateDetailsDOs != null && templateDetailsDOs.size() > 0) {
                //获得试卷模板的题目组成
                int one = 0;//暂定单选
                int two = 0;//暂定多选
                for (TemplateDetailsDO templateDetailsDO : templateDetailsDOs) {
                    if (templateDetailsDO.getType() == 0) {
                        one = one + templateDetailsDO.getTitleNumber();
                    } else if (templateDetailsDO.getType() == 1) {
                        two = two + templateDetailsDO.getTitleNumber();
                    }
                }

                int singleNum = 1;
                int multipleNum = one + 1;
                int judgeNum = one + two + 1;

                //从题库中查询并将信息添加至试卷试题
                for (TemplateDetailsDO templateDetailsDO : templateDetailsDOs) {

                    //暂时去除实操题的生成
                    if (templateDetailsDO.getType() != 3) {
                        CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(cn.getId());
                        if (certificateNewsDO != null) {
                            Map<Object, Object> map = new HashMap<>();
                            map.put("kpointsId", templateDetailsDO.getKpointsId());//templateDetailsDO.getKpointsId()); 当前默认为空，不做限制
                            map.put("profileId", profile_id);//certificationBatchDO.getProfileId());
                            map.put("topicTypes", templateDetailsDO.getType());
                            //map.put("item_bank_type", "0"); //只用练习题  0：练习题;1：考试题;不加这条则取所有题库

                            if (grade.equals("0")) { //certificateNewsDO.getGrade() == 0
                                map.put("grade", "高级");
                            } else if (grade.equals("1")) {//certificateNewsDO.getGrade() == 1
                                map.put("grade", "中级");
                            } else if (grade.equals("2")) {//certificateNewsDO.getGrade() == 2
                                map.put("grade", "初级");
                            }
                            map.put("titleNumber", templateDetailsDO.getTitleNumber());
                            List<Map<Object, Object>> maps = itemBankService.selRandList(map);//目前已经是根据单个知识点直接查询，已经调整了like查询了
                            if (maps != null && maps.size() > 0) {
                                for (int i = 0; i < maps.size(); i++) {
                                    //ExaminationQuestionsDO examinationQuestionsDO = new ExaminationQuestionsDO();
                                    Map testPaperMap = new HashMap();//试题明细

                                    testPaperMap.put("id", retQuestions.size() + 1);//examinationPaperDO1.getId()
                                    testPaperMap.put("topicTypes", maps.get(i).get("topicTypes"));
                                    testPaperMap.put("introduce", maps.get(i).get("topicContent").toString());
                                    testPaperMap.put("options", maps.get(i).get("options").toString());
                                    testPaperMap.put("answer", maps.get(i).get("rightKey").toString());
                                    testPaperMap.put("score", templateDetailsDO.getScore());
                                    testPaperMap.put("topicAnalysis", maps.get(i).get("topicAnalysis"));

                                    testPaperMap.put("resourceType", maps.get(i).get("resourceType"));

                                    if (templateDetailsDO.getType() == 0) {//单选
                                        testPaperMap.put("titleNumber", singleNum);//题号
                                        singleNum = singleNum + 1;
                                    } else if (templateDetailsDO.getType() == 1) {//多选
                                        testPaperMap.put("titleNumber", singleNum);//题号
                                        multipleNum = multipleNum + 1;
                                    } else if (templateDetailsDO.getType() == 2) {//判断
                                        testPaperMap.put("titleNumber", singleNum);//题号
                                        judgeNum = judgeNum + 1;
                                    }
                                    retQuestions.add(testPaperMap);//添加试卷试题
                                }
                            } else {
                                return ApiResult.fail("试卷模板中对应的知识点暂无相应题目，生成试卷失败，请检查并稍后重试！");
                            }
                        } else {
                            return ApiResult.fail("认证批次中的证书信息等级有误，生成试卷失败，请检查并稍后重试！");
                        }
                    }
                }
            } else {
                return ApiResult.fail("试卷模板详情信息有误或没有信息，生成试卷失败，请检查并稍后重试！");
            }
            mapre.put("questions", retQuestions);//添加试卷试题
        }
//                }  else {
//                    return ApiResult.fail("非理论考试批次暂时还不能生成试卷！");
//                }
        //}
        // }// end if  else
        //用循环检验是否还存在重复
//        String value;
//        int pp=0;
//        String sss="";
//        for(int i=0;i<100;i++){
//            value=retQuestions.get(i).get("introduce").toString();
//
//            for(int ia=0;ia<retQuestions.size();ia++){
//                if(value.equals(retQuestions.get(ia).get("introduce").toString())){
//                    pp++;
//                    sss+=sss+","+retQuestions.get(ia).get("id");
//                }
//            }
//            if(pp>1){
//                System.out.println("---------------------");
//                System.out.println("---------------------");
//                System.out.println("---------------------");

//                System.out.println("---------------------");
//                System.out.println("---------------------");
//                System.out.println("---------------------");
//                System.out.println("存在题目重复================="+value+"----"+"id=="+retQuestions.get(i).get("id")+"sss="+sss);
//            }
//            pp=0;
//            sss="";
//        }

        return ApiResult.success(mapre);

        /**
         Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
         if (map == null) {
         Map mapre = new HashMap();
         ExaminationPaperDO examinationPaperDO;
         examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 1);
         if (examinationPaperDO != null) {
         mapre.put("id", examinationPaperDO.getId());//试卷id
         mapre.put("name", examinationPaperDO.getName());//试卷名称
         mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号
         mapre.put("endTime",  );//结束时间

         Map map1 = new HashMap();
         map1.put("epaperId", examinationPaperDO.getId());
         List<TestPaperVo> testPaperVos = examinationQuestionsService.selTestPaper(map1);
         mapre.put("questions", testPaperVos);//试卷试题

         return ApiResult.success(mapre);
         } else {
         return ApiResult.fail("暂无试卷！");
         }
         } else {
         return ApiResult.success(map);
         }
         **/

    }

    /**
     * 证书刷题接口
     *
     * @return
     */
    @PostMapping("/yysSelByAll")
    @Log("考试程序端-考模拟考试试卷接口")
    @ApiOperation(value = "考试程序端-考模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> ItemBank(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        //获取用户信息
        UserDO user = this.getClientUser(token);
        Set<String> strings = menuService.listPerms(user.getId());
        if (strings.contains("lainxiquxian")){
            List<Map<Object, Object>> list = certificateProfileService.selByAll();
            //中级育婴员，中级保育师，中级养老护理员
            List<Map<Object, Object>> mapList = new ArrayList<>();
            for (Map li : list) {
                if (li.get("name").toString().indexOf("育婴员四级") != -1) {
                    li.put("num", 100);

                    mapList.add(li);
                }
                if (li.get("name").toString().indexOf("育婴员五级") != -1) {
                    li.put("num", 100);

                    mapList.add(li);
                }
                if (li.get("name").toString().indexOf("保育师四级") != -1) {


                    li.put("num", 100);
                    mapList.add(li);
                }
                if (li.get("name").toString().indexOf("保育师五级") != -1) {


                    li.put("num", 100);
                    mapList.add(li);
                }
                if (li.get("name").toString().indexOf("养老护理员") != -1) {


                    li.put("num", 100);
                    mapList.add(li);
                }

                if (li.get("name").toString().indexOf("育婴员高级") != -1) {


                    li.put("num", 100);
                    mapList.add(li);
                }

                if (li.get("name").toString().indexOf("育婴员三级") != -1) {


                    li.put("num", 100);
                    mapList.add(li);
                }
            }

            //育婴员，中级保育师，中级养老护理员
            return ApiResult.success(mapList);
        }else {
            return ApiResult.fail("用户没有权限，请联系管理员增加权限！");
        }
//
    }

    /**
     * 考试程序端-考模拟考试试卷接口
     *
     * @Description: 获得模拟考试试卷数据，包括试卷id、试卷编号、试卷名称、限时、题目、选项、题号
     * 参数：考试批次id
     * @Param: [profile_id]  证书概况id
     * @Param: [grade]  证书等级 （0高级，1中级，2初级）
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selYuyinExaminationPaper")
    @Log("小程序端-育婴员模拟考试试卷接口")
    @ApiOperation(value = "小程序端-育婴员模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})

    public ApiResult<?> selYuyinExaminationPaper(@RequestHeader(value = TOKEN_TAG, required = false) String token,Long profileId, Integer num) {

        //获取用户信息
        UserDO user = this.getClientUser(token);
        Set<String> strings = menuService.listPerms(user.getId());
        if (strings.contains("lainxiquxian")){
        String profile_id = profileId.toString(); //育婴员

        //jz_training_certificates
        List<CertificateProfileDO> trainingCertificatesDO = certificateProfileService.findByKv("id", profile_id);
        if (trainingCertificatesDO.size() > 0) {
            boolean isno = false;
            String maxDuration = null;
            if (trainingCertificatesDO.get(0).getName().indexOf("育婴员") != -1) {

                Map mapstus = new HashMap();
                mapstus.put("name", "育婴员刷题开关");
                mapstus.put("type", "yysOffNo");
                maxDuration = dictService.selDicBy(mapstus);
                if (maxDuration.equals("1")) {
                    isno = true;
                }
            }
            if (trainingCertificatesDO.get(0).getName().indexOf("保育师") != -1) {
                Map mapstus1 = new HashMap();
                mapstus1.put("name", "保育师刷题开关");
                mapstus1.put("type", "bysOffNo");
                maxDuration = dictService.selDicBy(mapstus1);
                if (maxDuration.equals("1")) {
                    isno = true;
                }
            }
            if (trainingCertificatesDO.get(0).getName().indexOf("养老护理员") != -1) {
                Map mapstus2 = new HashMap();
                mapstus2.put("name", "养老护理员刷题开关");
                mapstus2.put("type", "ylhlOffNo");
                maxDuration = dictService.selDicBy(mapstus2);
                if (maxDuration.equals("1")) {
                    isno = true;
                }

            }

            if (isno) {
                return ApiResult.fail("暂为开放！");
            }


        }


        Map m = new HashMap<String, String>();
        m.put("name", "育婴员题库练习");
        m.put("type", "yuyin_brushTopic_on-off");
        String examNotes = dictService.selDicBy(m);
        if (!examNotes.equals("on")) {
            return ApiResult.fail("无法访问");
        }


        Map mapre = new HashMap(); //返回值
        mapre.put("id", "000000");//试卷id
        mapre.put("name", "");//试卷名称
        mapre.put("numbers", "");//试卷编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        mapre.put("endTime", DateTimeUtil.getPostponeTimesOradvanceTimes(new Date(), -1));//结束时间
        ArrayList<Map> retQuestions = new ArrayList<>();
        //限制只查100个
        num=100;
        Map map = new HashMap();
        map.put("item_bank_type", 0);
        map.put("profileId", profile_id);
        map.put("titleNumber", num);

        List<ItemBankDO> maps = itemBankService.selRandLists(map);

        if (maps != null && maps.size() > 0) {
            for (int i = 0; i < maps.size(); i++) {
                //ExaminationQuestionsDO examinationQuestionsDO = new ExaminationQuestionsDO();
                Map testPaperMap = new HashMap();//试题明细

                testPaperMap.put("id", i + 1);//examinationPaperDO1.getId()
                testPaperMap.put("topicTypes", maps.get(i).getTopicTypes());
                testPaperMap.put("introduce", maps.get(i).getTopicContent());
                testPaperMap.put("options", maps.get(i).getOptions());
                testPaperMap.put("answer", maps.get(i).getRightKey());
                testPaperMap.put("score", 1);
                testPaperMap.put("topicAnalysis", maps.get(i).getTopicAnalysis());
                testPaperMap.put("resourceType", maps.get(i).getResourceType());
                testPaperMap.put("titleNumber", i + 1);//题号
                retQuestions.add(testPaperMap);//添加试卷试题
            }
        } else {
            return ApiResult.fail("题库中暂未题目，请检查并稍后重试！");
        }
        mapre.put("questions", retQuestions);//添加试卷试题

        return ApiResult.success(mapre);
        }else {
            return ApiResult.fail("用户没有权限，请联系管理员增加权限！");
        }


    }


    /**
     * 考试程序端-考试答卷提交接口
     *
     * @Description: 考生提交考卷；参数：考生id，试卷id，答卷集合
     * @Param: [stuSignId, epaperId, answerList]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-27
     */
    @PostMapping("/selAnswerSheet")
    @Log("考试程序端-考试答卷提交接口")
    @ApiOperation(value = "考试程序端-考试答卷提交接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selAnswerSheet(String stuSignId, String epaperId, String answerList, String code) {
        if (StringUtils.isBlank(stuSignId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(epaperId)) {
            return ApiResult.lack("");//缺少参数
        }

//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//        if (request != null) {
//            String userIp = IPUtils.getIpAddr(request);
//            if(userIp.equals("127.0.0.1")){
//                return ApiResult.fail("提交失败，请重试！");
//            }
//        }

        StuSignUpDO stuSignUpDO = stuSignUpService.selectById(Long.parseLong(stuSignId));
        if (stuSignUpDO != null) {
            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(currentTime);
            boolean bb = MD5Util.verify(stuSignUpDO.getTicketNumber(), dateString, code);
            if (bb) {
                ExaminationAnswerSheetDO examinationAnswerSheetDO = examinationAnswerSheetService.findOneByKv("epaper_id", epaperId, "stu_sign_id", stuSignId);
                if (examinationAnswerSheetDO != null) {
                    return ApiResult.fail("试卷已提交，如有问题请联系监考员");
                } else {
                    //提交试卷新增绑定考试批次字段
                    ExaminationAnswerSheetDO examinationAnswerSheetDO1 = new ExaminationAnswerSheetDO();
                    examinationAnswerSheetDO1.setEpaperId(Long.parseLong(epaperId));//试卷id
                    examinationAnswerSheetDO1.setStuSignId(Long.parseLong(stuSignId));//考生id
                    examinationAnswerSheetDO1.setAnswerList(answerList);//答卷集合
//                    Wrapper<StuSignUpDO> wrapper = new EntityWrapper<StuSignUpDO>();
//                    wrapper.eq("cbatch_id",Long.parseLong(stuSignId));
//                  List<StuSignUpDO> list=  stuSignUpService.selectList(wrapper);
//                    if(list.size()>0){
//                        //新增考试批次ID绑定
//                        examinationAnswerSheetDO1.setBatchId();
//                    }else {
//
//                    }
                    boolean b = examinationAnswerSheetService.insert(examinationAnswerSheetDO1);
                    if (b) {
                        stuSignUpDO.setState(10);
                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
                        if (bbc) {
                            return ApiResult.success("提交成功");
                        } else {
                            return ApiResult.fail("提交失败，请重试");
                        }
                    } else {
                        return ApiResult.fail("提交失败，请重试！");
                    }
                }
            } else {
                saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + epaperId + ";" + answerList, stuSignUpDO.getUserId(), stuSignUpDO.getName());
                return ApiResult.fail("信息错误，请重试");
            }
        } else {
            saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + epaperId + ";" + answerList, -2L, "不明来历者");
            return ApiResult.fail("信息错误，请重试");
        }
    }

    private void saveLog(String valuess, String params, Long id, String name) {
        LogDO sysLog = new LogDO();
        sysLog.setOperation(valuess + "，访问异常，请注意！");
        sysLog.setParams(params);
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (request != null) {
            sysLog.setMethod(request.getMethod() + " " + request.getRequestURI());
            // 设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
        }
        // 用户名
        sysLog.setUserId(id);
        sysLog.setUsername(name);
        sysLog.setTime(11);
        sysLog.setGmtCreate(new Date());
        // 保存系统日志
        logService.insert(sysLog);
    }

}
